import axios from "axios";
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig, AxiosError } from "axios";
import Nprogress from "nprogress";
import { getUserInfo } from "@/utils/localStorage.ts";
import { UserInfo } from "@/types/userTypes.d.ts";

export const baseURL: string = import.meta.env.VITE_APP_SERVER;

const request: AxiosInstance = axios.create({
    baseURL,
    timeout: 10000,
});

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    Nprogress.start();
    const userInfo:UserInfo=getUserInfo<UserInfo>()
    if (userInfo){
        config.headers.Authorization=`Bearer ${userInfo.token}`
    }
    return config;
}, (error: AxiosError) => {
    return error;
});

request.interceptors.response.use((response: AxiosResponse) => {
    Nprogress.done();
    const data = response.data;
    if (data.code !== 10000) {
        return Promise.reject(new Error(data.message));
    } else {
        return data;
    }
}, (error: AxiosError) => {
    Nprogress.done();
    return error;
});

export default request;
